import type { TabsMenuProps } from '@/stores/interface'
import { useKeepAliveStore } from './keepAlive'

const keepAliveStore = useKeepAliveStore()

export const useTabsStore = defineStore('tabs', () => {
  const router = useRouter()

  const tabsList = ref<TabsMenuProps[]>([])

  const addTabs = (tabItem: TabsMenuProps) => {
    if (tabsList.value.every((item) => item.path.split('?')[0] !== tabItem.path.split('?')[0])) {
      tabsList.value.push(tabItem)
    } else {
      const _item = tabsList.value.find(
        (item) => item.path.split('?')[0] === tabItem.path.split('?')[0]
      )
      if (_item) _item.path = tabItem.path
    }
    if (!keepAliveStore.keepAliveName.includes(tabItem.path) && tabItem.isKeepAlive) {
      keepAliveStore.addKeepAliveName(tabItem.path)
    }
  }
  const removeTabs = (removePath: string, isCurrent = false) => {
    if (isCurrent) {
      tabsList.value.forEach((item, index) => {
        if (item.path !== removePath) return
        const nextTab = tabsList.value[index + 1] || tabsList.value[index - 1]
        if (!nextTab) return
        router.push(nextTab.path)
      })
    }
    const tabItem = tabsList.value.find((item) => item.path === removePath)
    tabItem?.isKeepAlive && keepAliveStore.removeKeepAliveName(tabItem.path)
    tabsList.value = tabsList.value.filter((item) => item.path !== removePath)
  }
  const closeTabsOnSide = (path: string, type: 'left' | 'right') => {
    const currentIndex = tabsList.value.findIndex((item) => item.path === path)
    if (currentIndex !== -1) {
      const range = type === 'left' ? [0, currentIndex] : [currentIndex + 1, tabsList.value.length]
      tabsList.value = tabsList.value.filter((item, index) => {
        return index < range[0] || index >= range[1] || !item.close
      })
    }
    const KeepAliveList = tabsList.value.filter((item) => item.isKeepAlive)
    keepAliveStore.setKeepAliveName(KeepAliveList.map((item) => item.path))
  }
  // 关闭其他/关闭所有
  const closeMultipleTab = async (tabsMenuValue?: string) => {
    tabsList.value = tabsList.value.filter((item) => {
      return item.path === tabsMenuValue || !item.close
    })
    const KeepAliveList = tabsList.value.filter((item) => item.isKeepAlive)
    keepAliveStore.setKeepAliveName(KeepAliveList.map((item) => item.path))
  }
  const setTabs = (tabsMenuList: TabsMenuProps[]) => {
    tabsList.value = tabsMenuList
  }

  return {
    tabsList,
    addTabs,
    removeTabs,
    closeTabsOnSide,
    closeMultipleTab,
    setTabs
  }
})
